import os.path

from aiogram import Bot, types
from aiogram.types import FSInputFile
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from poker_bot.core.constants import ASSETS_FOLDER
from poker_bot.core.models.enums.user import UserRole
from poker_bot.database.services import AccountService, UserService
from poker_bot.tg_bot.keyboards.inline import account_confirmation_kb
from poker_bot.tg_bot.services.tg_helpers import broadcast


async def create_user_account(
    message: types.Message, _, manager: DialogManager, account_id: int, **kwargs
):
    """Создаем аккаунт пользователя"""

    bot: Bot = manager.middleware_data.get("bot")
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    user_service: UserService = manager.middleware_data.get("user_service")
    account_service: AccountService = manager.middleware_data.get("account_service")

    if not 6 <= len(str(account_id)) <= 8:
        await message.answer_photo(
            FSInputFile(os.path.join(ASSETS_FOLDER, "id_example.jpg")),
            caption=locale.get("wrong-account-id"),
        ),
        return

    account = await account_service.create_account(
        message.from_user.id, int(account_id)
    )
    user_accounts = await account_service.get_user_accounts(message.from_user.id)

    admins = await user_service.get_users_with_role(UserRole.admin)
    await broadcast(
        bot,
        admins,
        locale.get("new-account-for-confirmation-msg", account_id=str(account.id)),
        reply_markup=account_confirmation_kb(locale, account_id=account.id),
    )
    await message.answer(locale.get("moderation-msg"))
    if len(user_accounts) > 1:
        await manager.done()
    else:
        await message.answer(locale.get("first-account-added-msg"))
        await manager.reset_stack()
